# -*- coding: utf-8 -*-
import wsgiref.handlers
import xmw
import xmw.error
from xmw.dispatcher.event import *

from google.appengine.ext import webapp
from xmw.tianya import tianya_msg_utils

class MsgBuilder():
    pass

class MainPage(xmw.RequestHandler):    
    def get(self):
        msg_q=Msg.all()
        msg_q.filter("direction =", MsgDirection.IN)
        msg_q.filter("status =", MsgStatus.ON)
        
        msg=msg_q.get()
        if msg is None:
            e=xmw.error.NO_MSG_IN_QUEUE("")
            self.render_error(e)
            return
        
        name = msg.name
        helper=tianya_msg_utils.get_msg_helper(name)
        
        if helper is None:
            e=xmw.error.UNSUPPORTED_MSG(name)
            self.render_error(e)
            return 
        helper.handle_msg(msg)
        
        self.render_error(xmw.error.OK("create thread :%s"%msg.thread_id))
        


def main():
  application = webapp.WSGIApplication(
                                       [('/dispatcher/handle_msg', MainPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()